import {
  Breadcrumb,
  Button,
  Card,
  Form,
  Input,
  message,
  Modal,
  Radio,
  Space,
  Upload,
} from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import Channel from 'component/Channel';
import { Link } from 'react-router-dom';
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';
import styles from './index.module.scss';
import { useEffect, useRef, useState } from 'react';
import { getToken } from 'utils/storage';
import { baseURL } from 'utils/request';
import { useHistory } from 'react-router-dom';
import {
  ArticleAddAPI,
  getArticlePublishByIdAPI,
  ArticleEditByIdAPI,
} from 'api/article';
import { useParams } from 'react-router-dom';

export default function ArticlePublish() {
  // 动态路由中可以使用 props.match.params 中拿到动态路由传过来的值
  // console.log(_props.match.params.id);
  const [imgType, setImgType] = useState(1);
  const [imgUrl, setImgUrl] = useState('');
  const [fileList, setFileList] = useState([]);
  const draftRef = useRef(false);
  const formRef = useRef(null);
  // 也可以使用 hooks 来快速拿到 动态路由传过来的值 useParams
  // 快速拿到动态路由id
  const params = useParams();
  const { id } = params;
  // 回显数据
  const getArticlePublishById = async (id) => {
    const res = await getArticlePublishByIdAPI(id);
    // console.log(res);
    // console.log(formRef);
    // setFieldsValue From实例，用来设置表单值（只能更新有name字段）
    formRef.current.setFieldsValue({ ...res.data, type: res.data.cover.type });
    // 封面的显示
    setImgType(res.data.cover.type);
    // 图片的回显
    setFileList(res.data.cover.images.map((item) => ({ url: item })));
  };
  useEffect(() => {
    // 判断id是否存在
    if (id) {
      getArticlePublishById(id);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // 快速拿到history
  const history = useHistory();

  const props = {
    name: 'image',
    // 接受上传的文件类型
    accept: '.jpg,.jpeg,.png',
    action: `${baseURL}/v1_0/upload`,
    headers: {
      authorization: `Bearer ${getToken()}`,
    },
    onChange(info) {
      setFileList(info.fileList);
      if (info.file.status === 'done') {
        message.success(`${info.file.name} 上传成功`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 上传失败`);
      }
    },
    onPreview(file) {
      setImgUrl(file.url || file.thumbUrl);
    },
    beforeUpload(file) {
      // 设置白名单
      const typeWhite = ['image/jpg', 'image/jpeg', 'image/png'];
      if (!typeWhite.includes(file.type)) {
        message.warning('上传类型不对');
        return Upload.LIST_IGNORE;
      }
    },
  };
  // eslint-disable-next-line array-callback-return
  const showFileList = fileList.filter((item, index) => {
    if (imgType === 0) return false;
    if (imgType === 1) return index === 0;
    if (imgType === 3) return true;
  });
  const handleSubmit = async (values) => {
    // console.log(values);
    const formData = { ...values };
    formData.cover = {
      type: imgType,
      // 这里需要注意，存在两种情况，一是后台没有数据，需要从response中拿，二是后台有数据，直接从后台拿。因此需要做出判断
      images:
        imgType === 0
          ? []
          : showFileList.map((item) => item.url || item.response.data.url),
    };
    delete formData.type;
    // 判断上传图片长度是否相等
    if (fileList.length < imgType) {
      message.warning(`需要上传${imgType}张图片`);
      return;
    }
    // console.log(formData);
    // 判断是编辑还是发布
    if (id) {
      // 编辑
      await ArticleEditByIdAPI({ ...formData, id }, draftRef.current);
      message.success('编辑成功');
    } else {
      // 发布
      await ArticleAddAPI(formData, draftRef.current);
      message.success('发布成功');
    }
    history.push('/list');
  };
  return (
    <div style={{ paddingTop: 24 }} className={styles.root}>
      <Card
        title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>{id ? '编辑文章' : '发布文章'}</Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        <Form
          ref={formRef}
          size="large"
          name="basic"
          labelCol={{
            span: 3,
          }}
          wrapperCol={{
            span: 21,
          }}
          autoComplete="off"
          initialValues={{ content: '', type: 1 }}
          onFinish={handleSubmit}
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[
              {
                required: true,
                message: '请输入标题',
              },
            ]}
          >
            <Input style={{ width: 400 }} placeholder="请选择文章标题" />
          </Form.Item>

          <Form.Item
            label="频道"
            name="channel_id"
            rules={[
              {
                required: true,
                message: '请输入频道',
              },
            ]}
          >
            <Channel
              style={{ width: 200 }}
              placeholder="请选择文章频道"
            ></Channel>
          </Form.Item>

          {/* 富文本 */}
          {/* 这里需要注意，给富文本添加name属性，需要设置其默认值 */}
          <Form.Item
            label="内容"
            name="content"
            rules={[
              {
                required: true,
                message: '内容不能为空',
              },
              {
                validator: (_, value) => {
                  if (value === '<p><br></p>') {
                    return Promise.reject(new Error('内容不能为空'));
                  }
                  return Promise.resolve();
                },
              },
            ]}
          >
            <ReactQuill />
          </Form.Item>

          {/* 上转图片 */}
          <Form.Item label="封面" name="type">
            <Radio.Group onChange={(e) => setImgType(e.target.value)}>
              <Radio value={1}>单图</Radio>
              <Radio value={3}>三图</Radio>
              <Radio value={0}>无图</Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item
            wrapperCol={{
              // 从左往右偏移
              offset: 3,
            }}
          >
            <Upload {...props} listType="picture-card" fileList={showFileList}>
              {/* 限制上传图片，超过规定张数，隐藏上传组件 */}
              {fileList.length < imgType && (
                <Button icon={<PlusOutlined />}></Button>
              )}
            </Upload>
            <Modal
              visible={!!imgUrl}
              footer={null}
              onCancel={() => setImgUrl('')}
            >
              <img style={{ width: '100%' }} src={imgUrl} alt="" />
            </Modal>
          </Form.Item>

          <Form.Item
            wrapperCol={{
              // 从左往右偏移
              offset: 3,
            }}
          >
            <Space>
              <Button type="primary" htmlType="submit">
                {id ? '编辑文章' : '发布文章'}
              </Button>
              <Button
                type="primary"
                htmlType="submit"
                onClick={() => (draftRef.current = true)}
              >
                存入草稿
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
}
